<template>

  <div style="margin:40px;">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="margin:0;font-size:18px;font-weight:bold;">{{ this.$route.meta.title }}</span>
        <el-button style="float: right; padding:3px 0" type="text" @click="cancelForm">返回列表</el-button>
      </div>
      <div style="max-width:1000px;margin:auto;">
        <el-form
          ref="form"
          :model="form"
          :rules="form.houseType==0?rulesPesonal:rules"
          class="table-form"

          size="small"
        >
          <table class="table table-bordered th-bg">
            <tbody>
            <tr>
              <th width="200px">企业名称</th>
              <td>
                <el-form-item prop="enterpriseName">
                  <el-input v-model="form.enterpriseName"/>
                </el-form-item>
              </td>
            </tr>
              <tr v-if="!isEdit" v-for="(year, index) in years">
                <th width="200px">{{ year }}年产值（万元）</th>
                <td>
                  <el-form-item>
                    <el-input v-model="outputValues[index]" type="number">
                      <template slot="append">万元</template>
                    </el-input>
                  </el-form-item>
                </td>
              </tr>
              <tr v-if="isEdit" v-for="year in years">
                <th width="200px" >{{ year.key }}年产值（万元）</th>
                <td>
                  <el-form-item>
                    <el-input v-model="year.value" type="number">
                      <template slot="append">万元</template>
                    </el-input>
                  </el-form-item>
                </td>
              </tr>
              <tr>
                <th width="200px">企业简介</th>
                <td>
                  <el-form-item prop="profile" class="editor">
                    <div style="border: 1px solid #ccc;">
                      <Toolbar
                        style="border-bottom: 1px solid #ccc"
                        :editor="editor"
                        :defaultConfig="toolbarConfig"
                        :mode="mode"
                      />
                      <Editor
                        style="height: 500px; overflow-y: hidden; word-wrap: break-word;"
                        v-model="form.profile"
                        :defaultContent="defaultContent"
                        :defaultConfig="editorConfig"
                        :mode="mode"
                        @onCreated="onCreated"
                      />
                    </div>
                  </el-form-item>
                </td>
              </tr>
            </tbody>
          </table>
          <div style="display:flex; align-item: center; justify-content: center; margin-top:20px;">
            <el-button
              :loading="loading"
              type="primary"
              size="small"
              @click="submitForm"
            >
              {{isEdit ? '更新重点企业' : '新增重点企业'}}
            </el-button>
          </div>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import crudKey from '@/api/business/enterprise/key'
import { MessageBox } from 'element-ui'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
const defaultForm = {

}

export default {
  components: {
    Editor, 
    Toolbar
  },
  computed: {
    // ...mapGetters([
    //   'years',
    // ])
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: JSON.parse(JSON.stringify(defaultForm)),
      rules: {
        enterpriseName: [
          {
            required: true,
            message: '请输入企业名称'
          }
        ]
      },
      loading: false,
      id: null,
      years: [],
      outputValues: [],
      enterpriseName: null,
      editor: null,
      html: '',
      toolbarConfig: { 
        excludeKeys: [
	        'fullScreen',
          'uploadVideo',
          'uploadImage'
	      ]
      },
      editorConfig: { 
        placeholder: '请输入内容...',
        MENU_CONF: {
          lineHeight: {
            lineHeightList: ['0.5', '1', '1.5', '2', '2.5']
          }
        }
      },
      mode: 'default', // or 'simple'
      defaultContent : [
        {
          type: 'paragraph',
          lineHeight: '1.5',
          children: [
            { text: '', fontSize: '15px' },
          ]
        }
      ]
    }
  },

  created() {
    if (this.isEdit) {
      this.enterpriseName = this.$route.params && this.$route.params.id
      this.fetchData(this.enterpriseName)
    }else {
      this.years = JSON.parse(localStorage.getItem('years'))
    }
  },
  methods: {
    fetchData(enterpriseName) {
      crudKey.get(enterpriseName).then(response => {
        this.form = Object.assign({}, this.form, response.data)
        console.log(response.data)
        const keyValuePairs = response.data.outputValues.split(';');
        console.log(keyValuePairs)
        keyValuePairs.forEach(pair => {
          const [key, value] = pair.split(':');
          this.years.push({ key: key, value: value });
          console.log(this.years)
        });
        // if (response.data.fireFileList) {
        //   for (let i = 0; i < response.data.fireFileList.length; i++) {
        //     const item = response.data.fireFileList[i]
        //     const file = {
        //       fileId: item.fileId,
        //       name: item.fileName,
        //       url: `business/file/download?fileId=${item.fileId}`
        //     }
        //     this.fireFileList.push(file)
        //   }
        //   this.form.fireFileIdList = this.fireFileList.map(x => x.fileId)
        // }

      }).catch(err => {
        console.log(err)
      })
    },
    cancelForm() {
      this.$router.push('/business/enterprise/key')
    },

    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return
        }
        MessageBox.confirm('您确认执行此操作吗？', '确认操作', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          if (this.isEdit) {
            console.log('提交时进入isEdit')
            let output = '';
            for (let i = 0; i < this.years.length; i++) {
              output += `${this.years[i].key}:${this.years[i].value};`;
            }
            console.log(output)
            this.form.outputValues=output.slice(0, -1)
            crudKey.edit(this.form).then(() => {
              this.$notify({
                title: '成功',
                message: '修改信息成功',
                type: 'success',
                duration: 2000
              })
              this.loading = false
              this.cancelForm()
            }).catch(err => {
              console.log(err)
              this.loading = false
            })
          } else {
            let output = '';
            for (let i = 0; i < this.years.length; i++) {
              output += `${this.years[i]}:${this.outputValues[i]};`;
            }
            console.log(output)
            this.form.outputValues=output.slice(0, -1)
            crudKey.add(this.form).then(() => {
              this.$notify({
                title: '成功',
                message: '提交信息成功',
                type: 'success',
                duration: 2000
              })
              this.loading = false
              this.cancelForm()
            }).catch(err => {
              console.log(err)
              this.loading = false
            })
          }
        }).catch((e) => {
          console.log(e)
        });
      })
    },
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
  },
  mounted() {
    // 模拟 ajax 请求，异步渲染编辑器
    console.log(this.years)
    setTimeout(() => {
      this.html = '<p>模拟 Ajax 异步设置内容 HTML</p>'
    }, 1500)
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}

.amap-wrapper {
  width: 500px;
  height: 500px;
}

::v-deep .map-dialog .el-dialog__body {
  padding: 10px 20px;
}

</style>
<style src="@wangeditor/editor/dist/css/style.css"></style>
